#include <stdio.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_io.h"
#include "hi_gpio.h"
#include "iot_gpio.h"


#include "iot_errno.h"
#include "iot_uart.h"
#include "hi_uart.h"

#define KEY1_PIN 11
#define KEY2_PIN 12
unsigned int IoTGpioInit(unsigned int id);


#define GPIO_PIN_INIT    1
#define GPIO_PIN_UNINIT  0
static unsigned char g_gpioMap[HI_GPIO_IDX_MAX] = {0};
static unsigned char g_gpioInitNum = 0;

unsigned int IoTGpioInit(unsigned int id)
{
    if (id >= HI_GPIO_IDX_MAX) {
        return IOT_FAILURE;
    }

    if (g_gpioInitNum == 0) {
        (void)hi_gpio_init();
    }

    if (g_gpioMap[id] == GPIO_PIN_INIT) {
        return IOT_FAILURE;
    } else {
        g_gpioMap[id] = GPIO_PIN_INIT;
        g_gpioInitNum++;
    }

    return IOT_SUCCESS;
}

//按键1回调接口
static void Key1_EXIT_Callback(char *arg)
{
    printf("you are pressing the key_1.\n");
}

//按键2回调接口
static void Key2_EXIT_Callback(char *arg)
{
    printf("you are pressing the key_2.\n");
}

//按键线程
static void Button_Task_Start(void)
{
    while(1)
    {
        //延时500ms
        usleep(500*1000);
    }
}

static void ButtonDemoEntry(void)
{
    //初始化KEY1按键，设置为下降沿触发中断，中断回调函数为Key1_EXIT_Callback
    IoTGpioInit(KEY1_PIN);

    hi_io_set_func(KEY1_PIN, HI_IO_FUNC_GPIO_11_GPIO);
    //IoTGpioSetDir(KEY1_PIN, HI_GPIO_DIR_IN);
    hi_gpio_set_dir(KEY1_PIN, HI_GPIO_DIR_IN);
    hi_io_set_pull(KEY1_PIN, HI_IO_PULL_UP);
    //IoTGpioRegisterIsrFunc(KEY1_PIN, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, Key1_EXIT_Callback, NULL);
    hi_gpio_register_isr_function(KEY1_PIN, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, Key1_EXIT_Callback, NULL);


    //初始化KEY2按键，设置为下降沿触发中断，中断回调函数为Key2_EXIT_Callback
    IoTGpioInit(KEY2_PIN);
    hi_io_set_func(KEY2_PIN, HI_IO_FUNC_GPIO_12_GPIO);
    //IoTGpioSetDir(KEY2_PIN, HI_GPIO_DIR_IN);
    hi_gpio_set_dir(KEY1_PIN, HI_GPIO_DIR_IN);
    hi_io_set_pull(KEY2_PIN, HI_IO_PULL_UP);
    //IoTGpioRegisterIsrFunc(KEY2_PIN, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, Key2_EXIT_Callback, NULL);
    hi_gpio_register_isr_function(KEY1_PIN, IOT_INT_TYPE_EDGE, IOT_GPIO_EDGE_FALL_LEVEL_LOW, Key2_EXIT_Callback, NULL);

    //开启按键任务
    Button_Task_Start();
}

SYS_RUN(ButtonDemoEntry);